付小费的问题-代码实现

注:此方法所有计算都是手工的,一步一步来。 “小费问题”通常用来说明模糊逻辑原理从一组紧凑、直观的专家规则生成复杂行为的能力。

输入变量

在决定就餐时给多少小费时,有很多变量。考虑其中的两个:

输出变量

输出变量只是小费的数量,以百分比表示:

为了便于讨论,我们假设输入变量和输出变量都需要“高”、“中”和“低”隶属度函数。这些在scikit-fuzzy中定义如下

模糊规则

现在,为了使这些三角形有用,我们定义输入变量和输出变量之间的模糊关系。对于我们的例子,考虑三条简单的规则:

大多数人会同意这些规则,但这些规则是模糊的。将不精确的规则映射为定义的、可操作的提示是一项挑战。这是模糊逻辑擅长的一类任务。

规则应用

在以下情况下:

规则聚合(Rule aggregation)

已知单个隶属函数之后需要合并它们。这通常使用最大操作符来完成。这一步也被称为聚合。

去模糊化(Defuzzification)

最后,为了得到一个真实的世界答案,我们返回清晰值。我们这个例子中使用质心法。 结果是20.2%的小费。

结语

模糊系统是允许复杂的、直观的行为基于一个开销最小的规则稀疏系统。注意,我们的隶属度函数是粗糙的,仅在整数处定义,但fuzzy .interp_membership允许有效的分辨率随需求而增加。该系统可以对输入的任意小变化作出响应,处理负担最小。

To help understand what the membership looks like, use the view methods. These return the matplotlib Figure and Axis objects. They are persistent as written in Jupyter notebooks; other environments may require a plt.show() command after each .view().

Fuzzy rules

Now, to make these triangles useful, we define the fuzzy relationship between input and output variables. For the purposes of our example, consider three simple rules:

  1. If the food is poor OR the service is poor, then the tip will be low
  2. If the service is average, then the tip will be medium
  3. If the food is good OR the service is good, then the tip will be high. Most people would agree on these rules, but the rules are fuzzy. Mapping the imprecise rules into a defined, actionable tip is a challenge. This is the kind of task at which fuzzy logic excels.

Control System Creation and Simulation

Now that we have our rules defined, we can simply create a control system via:

In order to simulate this control system, we will create a ControlSystemSimulation. Think of this object representing our controller applied to a specific set of circumstances. For tipping, this might be tipping Sharon at the local brew-pub. We would create another ControlSystemSimulation when we're trying to apply our tipping_ctrl for Travis at the cafe because the inputs would be different.

We can now simulate our control system by simply specifying the inputsand calling the compute method. Suppose we rated the quality 6.5 out of 10 and the service 9.8 of 10.

Once computed, we can view the result as well as visualize it.

The resulting suggested tip is 19.84%.

Final thoughts

The power of fuzzy systems is allowing complicated, intuitive behavior based on a sparse system of rules with minimal overhead. Note our membership function universes were coarse, only defined at the integers, but fuzz.interp_membership allowed the effective resolution to increase on demand. This system can respond to arbitrarily small changes in inputs, and the processing burden is minimal.